# encoding=utf-8
import socket
import time
import matplotlib.pyplot as plt
HOST = '192.168.137.59'  # 服务器的ip
# 一号机192.168.137.84
# 二号机192.168.137.59
PORT = 6672  # 服务器端口
global plot_x
global plot_y
plot_x = []
plot_y = []
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # 以TCP协议模式进行通信
print("链接开始")
sock.connect((HOST, PORT))  # 连接服务器
plt.ion()
def plot_pos(A,B):  # 绘制飞行轨迹
    global plot_x
    global plot_y
    plt.clf()
    plot_x.append(A)
    plot_y.append(B)
    plt.figure(figsize=(10, 5))
    plt.plot(plot_x, plot_y)
    plt.scatter(plot_x, plot_y, s=10, c='red')
    plt.xlim(0, 6)
    plt.ylim(0, 3)
    plt.xticks(range(0, 6, 1))
    plt.yticks(range(0, 3, 1))
    plt.xlabel("Y")
    plt.ylabel("X")
    plt.show()
    plt.pause(1)

def monitor():
    print("Waiting for position information from server")
    while True:
        x=0
        y=0
        data=sock.recv(1024)
        data1 = data.decode()
        count = data1.split(',', 3)  # standard
        print(count)
        x = float(count[0])	#读取坐标信息
        y = float(count[1])
        mode = int(count[2]) #读取模式信息
        print("Received position: No.1 = x:",x,"y:",y)
        plot_pos(x,y)
        x_2=x-0.6
        y_2=y-1.5
        print("No.2 goal:",x_2,y_2)
        time.sleep(1)
        if (mode != 0): #执行模式不为0时，返回坐标和模式信息
            destation=[x_2,y_2]#收到坐标
            return destation,mode#接受坐标以及模式信息

while True:
    dest,mod=monitor() #直到接受到信息为止才会执行判断
    if (mod != 0):

        if (mod == 3):#退出循环，进入降落，关闭ip连接，关闭
            break

sock.close()#关闭连接
plt.close()#注释此行可以让程序结束运行后仍然保持图像

# 绘图
